package com.jisf.driver.filter;

import com.jisf.driver.exception.LoginException;
import com.jisf.driver.exception.TokenException;
import com.jisf.driver.response.ResultCode;
import com.jisf.driver.service.impl.UserDetailsImpl;
import com.jisf.driver.utils.JwtUtil;
import com.jisf.driver.utils.RedisUtil;
import com.jisf.driver.utils.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Classname JwtAuthenticationTokenFilter
 * @Description TODO Jwt认证过滤器
 * @Date 2022/4/7 15:17
 * @Created by jisf：【429627912@qq.com】
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if ("/user/login".equals(request.getRequestURI())){
            //不解析token，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        if (StringUtils.isBlank(token)){
            //不解析token，直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        Integer id;
        try {
            id = JwtUtil.getUserIdByJwtToken(token);
        }catch (TokenException e){
            throw new InternalAuthenticationServiceException(e.getMessage());
        }

        //从redis中获取用户信息
        String redisKey = "userId:" + id;
        UserDetailsImpl userDetails = redisUtil.getCacheObject(redisKey);
        if (Objects.isNull(userDetails)){
            throw new LoginException(ResultCode.USER_NOT_LOGIN);
        }

        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        UserUtil.userIdThreadLocal.set(id);
        UserUtil.usernameThreadLocal.set(userDetails.getUser().getUsername());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
